# ** Header **
import cherrypy
from backend.dbconnection import SQLQuery
from config import settings

# ** Body **
def isCorrectLogin(username, password):
    """
        foobar
    """
    sql = SQLQuery()
    sql.query("""SELECT `username` , `is_banned`
                 FROM `itf_users` 
                 WHERE `username` = CONVERT( _utf8 '%s'
                    USING latin1 ) 
                    COLLATE latin1_general_ci
                 AND `password` = CONVERT( _utf8 '%s'
                    USING latin1 ) 
                    COLLATE latin1_general_ci
                 LIMIT 0 , 1
              """ % (username, password))
    sql.close()
    return sql.res

def isLoggedIn():
    """
        foobar
    """
    prefix = settings['session_prefix']
    if cherrypy.session.has_key(prefix+"username") and cherrypy.session.has_key(prefix+"password"):
        print "session found!"
        return isCorrectLogin(cherrypy.session[prefix+'username'], cherrypy.session[prefix+'password']) 
    else:
        return False

def login(username, password):
    """
        foobar
    """
    prefix = settings['session_prefix']
    if isCorrectLogin(username, password):
        # Update 'Last login' field
        sql = SQLQuery()
        sql.query("""UPDATE `itf_users`
                     SET `last_visit` = NOW( )
                     WHERE CONVERT( `itf_users`.`username`
                        USING utf8 ) = '%s'
                     LIMIT 1 ;
                  """ % username)
        sql.close()
        updateActivity(username)
        # Set cookies
        cherrypy.session[prefix+'username'] = username
        cherrypy.session[prefix+'password'] = password
        return True
    else:
        return False
        
def logout():
    """
        foobar
    """
    prefix = settings['session_prefix']
    cherrypy.session.delete()
    return True

def updateActivity(username):
    """
        foobar
    """
    sql = SQLQuery()
    sql.query("""UPDATE `itf_users`
                    SET `last_activity` = NOW( )
                 WHERE CONVERT( `itf_users`.`username`
                    USING utf8 ) = '%s'
                 LIMIT 1 ;
              """ % username)
    sql.close()

    
